package com.anfeng.cms.service.impl.emp;

import com.anfeng.cms.common.Common;
import com.anfeng.cms.domain.emp.AfEmployeeInfo;
import com.anfeng.cms.domain.emp.AfEmployeePhoto;
import com.anfeng.cms.domain.emp.AfPhotoImpLog;
import com.anfeng.cms.request.upload.UploadImageBatchReq;
import com.anfeng.cms.request.upload.UploadImageBatchResp;
import com.anfeng.cms.service.emp.IAfEmployeeInfoService;
import com.anfeng.cms.service.emp.IAfEmployeePhotoService;
import com.anfeng.cms.service.emp.IAfPhotoImpLogService;
import com.anfeng.cms.service.emp.UploadImageService;
import com.anfeng.cms.util.IdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author 吴朋
 * @date 2019/7/15
 */
@Service
@Slf4j
public class UploadImageServiceImpl implements UploadImageService {

    @Autowired
    private IAfEmployeePhotoService afEmployeePhotoService;

    @Autowired
    private IAfEmployeeInfoService employeeInfoService;

    @Autowired
    private IAfPhotoImpLogService impLogService;

    @Value(value = "${af.filePath}")
    private String filePath;

    @Value(value = "${af.urlPath}")
    private String urlPath;

    /**
     * 保存图片信息
     * @param roleType 人员类型 访客和员工
     * @param empId 员工id
     * @param originName 图片名称
     * @param content 图片信息
     * @return 保存之后图片id
     */
    @Override
    public String saveImage(Integer roleType, String empId, String originName, byte[] content) throws Exception {
        if (StringUtils.isBlank(originName)) {
            log.error("原文件名不能为空");
            throw new Exception("原文件名不能为空");
        }
        if (content == null || content.length == 0) {
            log.error("文件内容不能为空");
            throw new Exception("文件内容不能为空");
        }
        String role = "emp";
        if (roleType == Common.PERSON_ROLE_TYPE_GUEST) {
            role = "guest";
        }

        String path = "/images/"+ role + "/";
        String id = IdGeneratorUtil.uuid();
        String imageName = id;
        if (originName.lastIndexOf(".") >= 0) {
            imageName += "." + originName.substring(originName.indexOf(".") + 1);
        }
        // 创建图片对象
        AfEmployeePhoto employeePhoto = new AfEmployeePhoto();
        employeePhoto.setId(id);
        if (roleType == Common.PERSON_ROLE_TYPE_EMPLOYEE) {
            employeePhoto.setEmpId(empId);
        } else {
            employeePhoto.setGuestId(empId);
        }
        employeePhoto.setName(imageName);
        employeePhoto.setState(Common.DATA_STATE_NORMAL);
        Date current = new Date();
        employeePhoto.setCreateTime(current);
        employeePhoto.setModifiedTime(current);

        String employeePath = filePath + path;
        //保存文件
        File dir = new File(employeePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String imageAllPath = employeePath + imageName;
        String shortPath = path + imageName;
        File file = new File(imageAllPath);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(content);
        } catch (IOException e) {
            throw new Exception("写文件失败");
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {/*do nothing*/}
            }
        }
        employeePhoto.setPath(shortPath);
        boolean isOk = afEmployeePhotoService.insert(employeePhoto);
        if (isOk) {
            return id;
        } else {
            log.error("文件插入数据库失败");
            throw new Exception("文件插入数据库失败");
        }
    }

    /**
     * 根据图片ID获取图片信息
     *
     * @param imageId 图片主键ID
     * @return 图片信息
     */
    @Override
    public AfEmployeePhoto getImageById(String imageId) {
        if (StringUtils.isBlank(imageId)) {
            log.error("资料ID不能为空!");
            return null;
        }
        return afEmployeePhotoService.selectById(imageId);
    }

    /**
     * 根据图片ID获取图片URL
     *
     * @param imageId 图片主键ID
     * @return 图片URL
     */
    @Override
    public String getImageUrlById(String imageId) {
        if (StringUtils.isBlank(imageId)) {
            log.error("资料ID不能为空!");
            return null;
        }
        AfEmployeePhoto uploadImage = afEmployeePhotoService.selectById(imageId);
        if(null == uploadImage) {
            return null;
        }
        String url = urlPath + uploadImage.getPath();
        log.info("文件下载路径：" + url);
        return url;
    }

    /**
     * 批量新增导入图片信息
     *
     * @param imageBatchReqs 图片信息
     * @return 导入结果
     */
    @Override
    public List<UploadImageBatchResp> uploadImageBatch(List<UploadImageBatchReq> imageBatchReqs) {
        if (null == imageBatchReqs || imageBatchReqs.isEmpty()) {
            log.error("批量导入图片信息 批量信息为空 或者不存在");
            return Collections.EMPTY_LIST;
        }
        List<UploadImageBatchResp> batchResps = new ArrayList<>();
        for (UploadImageBatchReq req : imageBatchReqs) {
            UploadImageBatchResp resp = new UploadImageBatchResp();
            resp.setPhotoName(req.getOriginName());

            // 新增导入记录
            AfPhotoImpLog impLog = new AfPhotoImpLog();
            impLog.setState(Common.DATA_STATE_NORMAL);
            Date currentDate = new Date();
            impLog.setCreateTime(currentDate);
            impLog.setModifiedTime(currentDate);
            impLog.setId(IdGeneratorUtil.uuid());
            impLog.setpName(req.getOriginName());

            AfEmployeeInfo employeeInfo = employeeInfoService.getEmployeeInfoByEmpNo(req.getOriginName());
            if (null == employeeInfo) {
                // 员工不存在
                resp.setRemark("根据照片名未查询到相关员工信息");
                batchResps.add(resp);

                impLog.setRemark("根据照片名未查询到相关员工信息");
                impLog.setSuccess(Common.UPLOAD_IMAGE_FAILED);
                boolean insert = impLogService.insert(impLog);
                if (!insert) {
                    log.error("新增导入图片记录失败 图片名:{}", req.getOriginName());
                }
                continue;
            }

            String imageId = null;
            try {
                // 保存成功
               imageId = this.saveImage(Common.PERSON_ROLE_TYPE_EMPLOYEE, employeeInfo.getId(), req.getOriginName(), req.getContent());
               // 获取图片地址
                AfEmployeePhoto photo = this.getImageById(imageId);
                if (null == photo) {
                    resp.setRemark("图片导入成功但是获取url失败");
                    impLog.setSuccess(Common.UPLOAD_IMAGE_FAILED);
                } else {
                    resp.setRemark("导入成功");
                    resp.setPath(photo.getPath());
                    impLog.setSuccess(Common.UPLOAD_IMAGE_SUCCESS);
                }
            } catch (Exception e) {
                resp.setRemark(e.getMessage());
                impLog.setSuccess(Common.UPLOAD_IMAGE_FAILED);
            }
            batchResps.add(resp);

            impLog.setpId(imageId);
            impLog.setRemark(resp.getRemark());
            boolean insertInfo = impLogService.insert(impLog);
            if (!insertInfo) {
                log.error("新增导入图片记录失败 图片名:{}", req.getOriginName());
            }
        }
        return batchResps;
    }
}
